/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
http://www.javamexico.org/foros/comunidad/hibernate_cache_carga_de_datos_en_tiempo_real



 */
package persistencia;
import excepciones.PersistenciaException;
import negocio.Complejo;
import net.sf.ehcache.hibernate.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
/**
 *
 * @author Diego
 */
public class Persistencia {
    private SessionFactory sessionFactory;
    private Session session;
    
    public Persistencia() {
        sessionFactory = new Configuration().configure().buildSessionFactory();
        session = sessionFactory.openSession();
    }
    
    public void insert(Object unObjeto) {
    Transaction tr = session.beginTransaction();
    session.save(unObjeto);
    tr.commit();
    }
    public void update(Object unObjeto){
        Transaction tr = session.beginTransaction();
            session.saveOrUpdate(unObjeto);
        tr.commit();
    }
    public void delete(Object unObjeto){
        Transaction tr = session.beginTransaction();
        session.delete(unObjeto);
        tr.commit();
    }
    public Complejo cargarComplejo(Integer unId) throws PersistenciaException{
        Complejo unComplejo = null;
        //Session session2 = HibernateUtil.getSessionFactory().getCurrentSession();
        //http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch01.html#tutorial-firstapp-workingpersistence
        try{
            unComplejo = (Complejo) session.get(Complejo.class, unId);
        }
        catch(Exception ex){
            throw new PersistenciaException("Error al cargar el complejo: "+ex.getMessage(),1);
        }
       /*finally{
            this.session.close();
        }*/
        return unComplejo;
    }
    
}
